<template>
  <div class="new-order">
    <a-form :form="newOrderForm">
      <a-row>
        <a-col :span="24"><div class="fwdz">{{ order.fwdz }}{{ order.fh }}&emsp;<span v-if="modify"><span @click="handlRoomChangeShow('true')" v-if="!isRoomChangeShow" class="roombtn">换房</span><span @click="handlRoomChangeShow('false')" v-else class="roombtn">取消</span></span></div></a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="pad_bot10">入住人员</a-col>
      </a-row>
      <template v-for="(i,index) in keys">
        <a-row :key="i" v-if="computedDelObj[`${index}`] !=='true'">
          <a-col :span="24">
            <a-row :gutter="12">
              <a-col :span="3">
                <a-form-item>
                  <a-input
                    maxLength="10"
                    v-decorator="[
                      `tenantsRequest[${index}].zkxm`,{
                        rules: [{
                          required: true,
                          pattern:nameReg,
                          message: '请输入正确的姓名'
                        }],
                        initialValue: tenantInfo&&tenantInfo.tenantsRequest[index]&&tenantInfo.tenantsRequest[index].zkxm
                      }
                    ]"
                    placeholder="姓名"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-input
                    maxLength="11"
                    v-decorator="[
                      `tenantsRequest[${index}].lxdh`,{
                        rules: [{
                          required: true,
                          pattern: phoneReg,
                          message: '请输入正确的手机号码'
                        },{validator: validatePhone}],
                        initialValue: tenantInfo&&tenantInfo.tenantsRequest[index]&&tenantInfo.tenantsRequest[index].lxdh,
                        validateFirst:true
                      }
                    ]"
                    @blur="handleLxdhBlur"
                    placeholder="手机号码"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item>
                  <a-select
                    placeholder="证件类型"
                    v-decorator="[
                      `tenantsRequest[${index}].zjzl`,{
                        rules: [{
                          required: true,
                          message: '请选择证件种类'
                        }],
                        initialValue: '1'
                      }
                    ]">
                    <a-select-option value="1">二代身份证</a-select-option>
                  <!-- <a-select-option value="2">护照</a-select-option> -->
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item>
                  <a-row :gutter="12">
                    <a-col :span="12">
                      <a-input
                        maxLength="18"
                        @blur="handleZjhmBlur"
                        v-decorator="[
                          `tenantsRequest[${index}].zjhm`,{
                            rules: [{
                              message: '请输入正确的证件号码',
                              pattern: cardIdReg
                            }, {validator: validateId}],
                            initialValue: tenantInfo&&tenantInfo.tenantsRequest[index]&&tenantInfo.tenantsRequest[index].zjhm,
                            validateFirst:true
                          }
                        ]"
                        placeholder="证件号码"></a-input>
                    </a-col>
                    <a-col :span="6">
                      <div class="person" v-if="index === 0" @click="addTanentInfo"><a-icon :component="iconAddPerson" style="margin-right:5px;"/>增加入住人</div>
                      <div class="person" v-else @click="delTannetInfo(index)"><a-icon :component="iconDelPerson" style="margin-right:5px"/>删除入住人</div>
                    </a-col>
                  </a-row>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </template>
      <a-row>
        <a-col :span="24" class="pad_bot10 pad_top10">入住时间</a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-item>
            <a-range-picker
              showTime
              v-decorator="[
                'rzldrq',
                {rules: [{ required: true, message: '请选择日期'}, {validator: validate}],
                 initialValue:[startTime, endTime]
                },
              ]"
              format="YYYY-MM-DD HH:mm:ss"
              :disabledDate="disabledDate"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              dropdownClassName="jlwDate" >
              <template slot="dateRender" slot-scope="current,tody">
                <div class="ant-calendar-date" :style="getCurrentStyle(current,tody)">
                  {{ current.date() }}
                  <span v-if="includesArray(current) === 1" style="font-size:12px;"><br/>预定</span>
                  <span v-else-if="includesArray(current) === 2" style="font-size:12px;"><br/>已住</span>
                </div>
              </template>
              <template slot="renderExtraFooter"><span id="msgClass">{{ msg }}</span></template>
            </a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="2"><div class="times">共{{ timesCup }}晚</div></a-col>
      </a-row>
      <a-row v-if="modify&&isRoomChangeShow">
        <div class="title pad_top28">换房号</div>
      </a-row>
      <a-row v-if="modify&&isRoomChangeShow">
        <a-col :span="12" >
          <a-form-item>
            <a-select
              @change="onRoomChange"
              v-decorator="['houseId', {
                rules: [{required: true,
                         message: '必填' }]
              }]"
              placeholder="请选择要换的房间号">
              <!-- <a-select-option :value="String(order.houseId)">{{ order.fh }}</a-select-option> -->
              <template v-if="rommData.length>0">
                <a-select-option v-for="(item) in rommData" :key="item.houseId" :value="String(item.houseId)">{{ item.fh }}</a-select-option>
              </template>
            </a-select>

          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>
<script>
import moment from 'moment'
import { addOrder, updateOrder, getOrdersByHouseId } from '@/api/order'
import { nameReg, phoneReg, cardIdReg } from '@/utils/reg'
import { mapGetters } from 'vuex'
import { iconAddPerson, iconDelPerson } from '@/core/icons'
import { timesDate, verifyRepeat } from '@/utils/util'
import { houseOrders } from '@/api/status'

export default {
  name: 'NewOrder',
  props: {
    order: {
      type: Object,
      default: () => { return {} }
    },
    modify: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      startTime: {},
      endTime: {},
      iconAddPerson,
      iconDelPerson,
      nameReg,
      phoneReg,
      cardIdReg,
      keys: 1,
      newOrderForm: '',
      times: 1, // 共几晚
      msg: '', // 日历页脚消息提示
      pickDisabled: [],
      delObj: {}, // 删除的数据
      rooms: [], // 可选房间列表
      isRoomChangeShow: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'currentSelectedDate',
      'OPERATOR_TYPE',
      'STORE_ID'
    ]),
    tenantInfo () {
      const orderTenantList = this.order.orderList[0].tenantList
      if (orderTenantList.length > 0) {
        const tenantInfo = orderTenantList
        const length = orderTenantList.length - 1
        const tenatlist = []
        for (let i = 0; i <= length; i++) {
          tenatlist.push({ zkxm: tenantInfo[i].zkxm, lxdh: tenantInfo[i].lxdh, zjhm: tenantInfo[i].zjhm })
        }
        return { tenantsRequest: tenatlist }
      } else {
        return ''
      }
    },
    // 计算删除的对象
    computedDelObj () {
      return this.delObj
    },
    timesCup () {
      return this.times
    },
    rommData () {
      return this.rooms
    }
  },
  methods: {
    /** 日历插件时间change
     * @param type等于2 说明是非人为触发改变时间事件，不需要获取房间list
    */
    onChange (value, dateString, type) {
      const dateArray = this.pickDisabled
      if (this.pickDisabled.length > 0) {
        let isfalse = true
        for (let i = 0; i < dateArray.length; i++) {
          if (moment(value[1]).isBefore(dateArray[i]['rzsj']) || moment(value[0]).isAfter(dateArray[i]['ldsj'])) {
            continue
          } else {
            isfalse = false
            break
          }
        }
        if (isfalse) {
          this.msg = ''
        } else {
          this.msg = '所选时间已有房源被占用'
        }
      } else {
        this.msg = ''
      }
      this.totalDate(value, dateString)
      // 修改的情况下才调用
      if (this.modify && type !== 2 && this.isRoomChangeShow) {
        this.roomList(moment(value[0]).format('YYYY-MM-DD HH:mm:ss'), moment(value[1]).format('YYYY-MM-DD HH:mm:ss'))
      }
    },
    // 日期禁用
    disabledDate (currentDate) {
      const dateArray = this.pickDisabled
      if (currentDate) {
        // currentDate <= moment(this.startTime).add(-1, 'day')
        if (currentDate < moment()) {
          return true
        } else {
          for (let i = 0; i < dateArray.length; i++) {
            if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
              return true
            }
          }
        }
      }
    },
    // 日历插槽样式
    getCurrentStyle (currentDate) {
      const dateArray = this.pickDisabled
      const style = {}
      style.width = '46px'
      style.minWidth = '46px'
      style.height = '46px'
      style.lineHeight = '46px'
      for (let i = 0; i < dateArray.length; i++) {
        if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
          style.position = 'relative'
          style.lineHeight = '1.5'
        }
      }
      return style
    },
    // 日历订单状态（）
    includesArray (currentDate) {
      const dateArray = this.pickDisabled
      for (let i = 0; i < dateArray.length; i++) {
        if (currentDate.isBetween(dateArray[i]['rzsj'], dateArray[i]['ldsj']) || currentDate.isSame(dateArray[i]['rzsj']) || currentDate.isSame(dateArray[i]['ldsj'])) {
          if (dateArray[i]['ddzt'] === '1') {
            return 1
          } else if (dateArray[i]['ddzt'] === '2') {
            return 2
          }
        }
      }
    },
    handleSubmit (type) {
      return new Promise((resolve, reject) => {
        const order = this.order
        // e.preventDefault()
        const orderRequest = {
          rzsj: '',
          ldsj: '',
          fwdz: order.fwdz,
          // fh: order.fh,
          houseId: order.houseId,
          hoperatorId: this.userInfo.id,
          storesId: this.STORE_ID,
          jylx: this.OPERATOR_TYPE,
          orderId: order['orderList'][0].orderId,
          tenantsRequest: []
        }
        this.newOrderForm.validateFieldsAndScroll(async (err, values) => {
          if (!err) {
            orderRequest.tenantsRequest = values.tenantsRequest
            // 过滤由删除影藏导致的无用数组索引
            const filterTenantsRequest = orderRequest['tenantsRequest'].filter((item) => {
              if (item) {
                return true
              }
            })
            orderRequest.tenantsRequest = filterTenantsRequest
            // end
            if (this.modify && this.isRoomChangeShow) {
              orderRequest.houseId = values['houseId']
            }
            orderRequest.rzsj = values['rzldrq'][0].format('YYYY-MM-DD HH:mm:ss')
            orderRequest.ldsj = values['rzldrq'][1].format('YYYY-MM-DD HH:mm:ss')
            let res = {}
            if (type === 'Add_ORDER') {
              res = await addOrder(orderRequest).catch((err) => {
                reject(err)
              })
            } else if (type === 'MODIFIER_ORDER') {
              res = await updateOrder(orderRequest).catch((err) => {
                reject(err)
              })
            }
            if (res.code === 2017) {
              let conflictStr = ''
              for (let i = 0; i < res.data.length; i++) {
                if (values['rzldrq'][1].isBefore(res.data[i]['rzsj']) || values['rzldrq'][0].isAfter(res.data[i]['ldsj'])) {
                  continue
                } else {
                  conflictStr += `${res.data[i]['rzsj']}--${res.data[i]['ldsj']};`
                  break
                }
              }
              conflictStr = `${conflictStr}已有订单，请重新选择！`
              this.$notification['warning']({
                message: this.$t('message.hint'),
                description: conflictStr,
                duration: 10
              })
              reject(err)
            } else {
              resolve(res)
            }
          } else {
            reject(err)
          }
        })
      })
    },
    handleReset () {
      this.newOrderForm.resetFields()
    },
    addTanentInfo () {
      this.keys += 1
    },
    delTannetInfo (index) {
      const selObj = {}
      selObj[index] = 'true'
      this.delObj = Object.assign(selObj, this.delObj)
      // 删除自动校验
      this.$nextTick(() => {
        const form = this.newOrderForm
        const selArray = form.getFieldValue('tenantsRequest')
        for (let i = 0; i < selArray.length; i++) {
          if (selArray[i]) {
            form.validateFields([`tenantsRequest[${i}].zjhm`], { force: true })
            form.validateFields([`tenantsRequest[${i}].lxdh`], { force: true })
          }
        }
      })
    },
    setOrder () {
      this.newOrderForm = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return {
            //
          }
        }
      })
    },
    // 多少晚
    totalDate (date, date2) {
      if (date2[0] !== '') {
        this.times = timesDate(date2[0], date2[1])
      } else {
        this.times = 0
      }
    },
    // 获取后台数据禁用数据获取日历
    getPickDate (houseId, curDate) {
      return new Promise((resolve, reject) => {
        getOrdersByHouseId({ houseId: houseId, cxsj: curDate }).then((res) => {
          this.pickDisabled = []
          const firstOrderId = this.order.orderList[0].orderId
          if (firstOrderId && firstOrderId !== 0) {
            if (res.data && res.data.length > 0) {
              const list = res.data.filter((item) => {
                if (item.orderId !== firstOrderId) {
                  return item
                }
              })
              this.pickDisabled = list
            } else {
              this.pickDisabled = res.data
            }
          } else {
            this.pickDisabled = res.data
          } resolve(this.pickDisabled)
        }).catch((error) => reject(error))
      })
    },
    validate (rule, value, callback) {
      if (value.length > 0) {
        const star = moment(value[0])
        const end = moment(value[1])
        if (end <= star) {
          callback(new Error('结束时间不能小于或等于开始时间'))
        }
        const dateArray = this.pickDisabled
        let isfalse = true
        for (let i = 0; i < dateArray.length; i++) {
          if (moment(value[1]).isBefore(dateArray[i]['rzsj']) || moment(value[0]).isAfter(dateArray[i]['ldsj'])) {
            continue
          } else {
            isfalse = false
            break
          }
        }
        if (isfalse) {
          callback()
        } else {
          callback(new Error('所选时间已有房源被占用'))
        }
      } else {
        callback()
      }
    },
    handleLxdhBlur (e) {
      const form = this.newOrderForm
      const selArray = form.getFieldValue('tenantsRequest')
      for (let i = 0; i < selArray.length; i++) {
        if (selArray[i]) {
          if (e.target.id !== `tenantsRequest[${i}].lxdh` && e.target.value) {
            form.validateFields([`tenantsRequest[${i}].lxdh`], { force: true })
          }
        }
      }
    },
    handleZjhmBlur (e) {
      const form = this.newOrderForm
      const selArray = form.getFieldValue('tenantsRequest')
      for (let i = 0; i < selArray.length; i++) {
        if (selArray[i]) {
          if (e.target.id !== `tenantsRequest[${i}].zjhm` && e.target.value) {
            form.validateFields([`tenantsRequest[${i}].zjhm`], { force: true })
          }
        }
      }
    },
    validatePhone (rule, value, callback) {
      const personalArray = this.newOrderForm.getFieldValue('tenantsRequest')
      if (value && personalArray.length > 0) {
        const istrue = verifyRepeat(personalArray, value, rule.field, 1, 'lxdh')
        if (istrue) {
          callback(new Error('联系电话不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    validateId (rule, value, callback) {
      const formt = this.newOrderForm
      const personalArray = formt.getFieldValue('tenantsRequest')
      if (value && personalArray.length > 0) {
        const istrue = verifyRepeat(personalArray, value, rule.field, 1, 'zjhm')
        if (istrue === true) {
          callback(new Error('证件号码不能重复'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    /**
     * 房号变动时间禁用切换
     */
    onRoomChange (val) {
      /* 获取日历数据传入房号 houseId */
      const cxsj = moment().format('YYYY-MM-DD HH:mm:ss')
      Promise.all([this.getPickDate(val, cxsj)]).then((res) => {
        const form = this.newOrderForm
        form.validateFields(['rzldrq'], { force: true })
        const time = form.getFieldValue('rzldrq')
        this.onChange(time, [moment(time[0]).format('YYYY-MM-DD HH:mm:ss'), moment(time[1]).format('YYYY-MM-DD HH:mm:ss')], 2)
      })
    },
    /**
     * 获取用户当前时间可用房间列表
     */
    roomList (rzsj, ldsj) {
      const data = {
        hoperatorId: this.userInfo.id,
        storesId: this.STORE_ID,
        jylx: this.OPERATOR_TYPE,
        ksrq: rzsj,
        jsrq: ldsj,
        fwrzzt: 3 // 3:未入住状态
      }
      houseOrders(data).then((res) => {
        // this.rooms = res.data.date.filter((item) => {
        //   if (item.houseId !== this.order.houseId) {
        //     return item
        //   }
        // })
        this.rooms = res.data.date
      }).catch((err) => { console.log(err) })
    },
    /**
     * 换房功能
     * @val false 是取消；true 是换房
     */
    handlRoomChangeShow (val) {
      const cxsj = moment().format('YYYY-MM-DD HH:mm:ss')
      const form = this.newOrderForm
      const time = form.getFieldValue('rzldrq')
      if (val === 'false') {
        /* 取消时要还原所有的数据 */
        Promise.all([this.getPickDate(this.order.houseId, cxsj)]).then((res) => {
          form.validateFields(['rzldrq'], { force: true })
          this.onChange(time, [moment(time[0]).format('YYYY-MM-DD HH:mm:ss'), moment(time[1]).format('YYYY-MM-DD HH:mm:ss')], 2)
          this.isRoomChangeShow = false
        })
      } else {
        this.roomList(moment(time[0]).format('YYYY-MM-DD HH:mm:ss'), moment(time[1]).format('YYYY-MM-DD HH:mm:ss'))
        this.isRoomChangeShow = true
      }
    }
  },
  watch: {
    currentSelectedDate (newVal) {
      if (newVal) {
        this.startTime = moment(newVal)
        this.endTime = moment(newVal).add(+1, 'days')
      }
    }
  },
  created () {
    this.newOrderForm = this.$form.createForm(this)
    if (this.tenantInfo) {
      const firstOrder = this.order['orderList'][0]
      this.keys = this.tenantInfo.tenantsRequest.length
      this.tenantsRequest = this.tenantInfo.tenantsRequest
      this.startTime = moment(firstOrder.rzsj)
      this.endTime = moment(firstOrder.ldsj)
      this.times = firstOrder.rzts
      /* 获取日历数据传入房号 houseId */
      const cxsj = moment().format('YYYY-MM-DD HH:mm:ss')
      this.getPickDate(this.order.houseId, cxsj)
    } else {
      const cutday = moment().format('YYYY-MM-DD')
      const cxsj = moment().format('YYYY-MM-DD HH:mm:ss')
      // const cxsj = moment(this.currentSelectedDate).format('YYYY-MM-DD HH:mm:ss')
      this.getPickDate(this.order.houseId, cxsj)
      // 是不是今天
      if (this.currentSelectedDate === cutday) {
        const cutHours = moment().get('hours')
        const cutMinutes = moment().get('minutes') + 1
        const cutSeconds = moment().get('seconds')
        this.startTime = moment(this.currentSelectedDate).set('hours', cutHours).set('minutes', cutMinutes).set('seconds', cutSeconds)
        // 当天，结束时间为第二天12点
        this.endTime = moment(this.startTime).add(+1, 'days').hours(12).set('minutes', 0).set('seconds', 0)
      } else {
        this.startTime = moment(this.currentSelectedDate).hours(14).set('minutes', 0).set('seconds', 0)
        this.endTime = moment(this.startTime).add(+1, 'days').hours(12)
      }
    }
  }

}
</script>
<style lang="less" scoped >
.new-order {
  .roombtn{color:#40a9ff;font-size: 14px;cursor: pointer;}
  .fwdz{
    height:24px;
    font-size:16px;
    font-weight:700;
    color:rgba(0,0,0,0.85);
    line-height:24px;
  }
  .times {
    width: 100%;
    text-align: center;
    position: absolute;
    top: 10px;
  }
  .person {
    cursor: pointer;
    color: #1890FF;
  }
}
 #msgClass{color:red;}
</style>
